#include "javascriptapi.h"
#include <mysettings.h>

JavaScriptApi::JavaScriptApi(QObject *parent) :
    QObject(parent),
    key(NULL)
{
}

QString JavaScriptApi::getUsers()
{
    QFile file(MySettings::dataPath("users.json"));
    file.open(QIODevice::ReadWrite);
    QString users = file.readAll();
    file.close();
    if(users.length() == 0)
        users = "{\"users\":[]}";
    return users;
}

void JavaScriptApi::setUsers(QString users)
{
    QFile file(MySettings::dataPath("users.json"));
    file.open(QIODevice::ReadWrite);
    file.write(users.toUtf8().constData());
    file.close();
    return;
}

QString JavaScriptApi::codePassword(QString password)
{
    generateKey();
    int len = password.length();
    QString text(len);
    for(int a = 0; a < len; a++)
        for(int b = 0; b < key->length(); b++)
            text[a] = QChar(password.at(a).toAscii() ^ (key->at(b).toAscii()));
    return text;
}

void JavaScriptApi::generateKey()
{
    if(!key)
    {
        QHostInfo host;
        QString str = host.localHostName()+QDir::homePath();
        str.append(str.length());
        QCryptographicHash hash(QCryptographicHash::Md5);
        hash.addData(str.toAscii());
        key = new QString(hash.result().toHex());
    }
}

void JavaScriptApi::ProxySettings()
{
    ProxyDlg * prDlg = new ProxyDlg();
    prDlg->setModal(true);
    prDlg->show();
}
